package csu.rjxyg.action.fileAction;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.bson.types.ObjectId;

import com.opensymphony.xwork2.ActionContext;

import csu.rjxyg.action.BaseAction;
import csu.rjxyg.action.constant.UserConstant;
import csu.rjxyg.bean.core.BaseObject;
import csu.rjxyg.factory.core.UtilFactory;
import csu.rjxyg.service.BaseUserService;
import csu.rjxyg.util.LogUtil;

public class ImgUploadAction extends BaseAction {
	private LogUtil log;
	
	private File file; //上传的文件
	private String fileContentType;
	private String fileFileName;
	
	public ImgUploadAction(){
		log = UtilFactory.getLogUtil(this.getClass());
	}
	
	public void userImgUpload() throws IOException{
		String name = null;
		try {
			BaseUserService userService = (BaseUserService) factory.getBean(BaseAction.USER_SERVICE);
			BaseObject object = (BaseObject) this.getSession().get(UserConstant.USER_SESSION);
			name = (String) object.get(UserConstant.USER_ID);
			
			String realpath = ServletActionContext.getServletContext().getRealPath("/tempImages");
			
	        String tempFile = new ObjectId().toHexString();
	        if (file != null) {
	            File savefile = new File(new File(realpath), tempFile);
	            if (!savefile.getParentFile().exists())
	                savefile.getParentFile().mkdirs();
	            FileUtils.copyFile(file, savefile);
	            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
	            Matcher m = p.matcher(tempFile);
	            tempFile =m .replaceAll("");
	            this.out("tempImages/" + tempFile);
	        }
		}catch (Exception e) {
			this.out("3");
			log.info(name + "新建用户信息失败");
			e.printStackTrace();
			log.info(e.getMessage());
		}
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	
	
}
